package com.ssm.reader.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ssm.reader.entity.*;
import com.ssm.reader.service.BookService;
import com.ssm.reader.service.CategoryService;
import com.ssm.reader.service.EvaluationService;
import com.ssm.reader.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/*
 *
 *图书控制器
 *@data 2022-04-29
 */
@Controller
public class BookController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private BookService bookService;
    @Resource
    private EvaluationService evaluationService;
    @Resource
    private MemberService memberService;

    /*
    * 显示首页
    *
    * */
    @GetMapping("/")
    public ModelAndView showIndex(){
        ModelAndView modelAndView = new ModelAndView("/index");
        List<Category> categories = categoryService.selectAll();
        modelAndView.addObject("categoryList",categories);
        return modelAndView;
    }


    /*
    * 分页查询图书列表
    * p 页号
    * return 分页对象
    *
    *
    * */
    @GetMapping("/books")
    @ResponseBody
    public IPage<Book> selectBook(Long categoryId,String order,Integer p){
        if (p == null)
        {
            p = 1;
        }
        IPage<Book> paging = bookService.paging(categoryId,order,p, 10);
        return paging;
    }

    @GetMapping("/book/{id}")
    public ModelAndView showDetail(@PathVariable("id") Long id, HttpSession session){
        Book book = bookService.selectById(id);
        List<Evaluation> evaluations = evaluationService.selectByBookId(id);
        Member member = (Member)session.getAttribute("loginMember");
        ModelAndView modelAndView = new ModelAndView("/detail");
        if (member != null){
            //获取阅读状态
            MemberReadState memberReadState = memberService.selectMemberReadState(member.getMemberId(), id);
            modelAndView.addObject("memberReadState",memberReadState);
        }
        //可能这个会员没有想看，也没有看过的状态
        modelAndView.addObject("book",book);

        modelAndView.addObject("evaluations",evaluations);
        return modelAndView;
    }
}
